#!/usr/bin/perl -w

use strict;

use lib "./lib";
use CGI;
use URI::Escape;
use HTML::Template;
use String::Random;
use DB::MailAccounts;

&main();

sub main() {
	my $q = new CGI;
	my $template = "../templates/index.tmpl";
	my $tmpl = new HTML::Template(filename => $template);

	print $q->header(-type => 'text/html', -charset => 'utf-8');

	my $email = $q->param("email");
    if (!defined($email)) {
        $email = "";
    } elsif(&validate_email_address($email)){
		$tmpl->param(registered => 1);
		&send_mail($email);
	}
    else {
        $email = "";
        $tmpl->param(invalid => 1); 
    }
	$tmpl->param(email => $email);

	print $tmpl->output;

}

sub validate_email_address {
    my $addr_to_check = shift;
    $addr_to_check =~ s/("(?:[^"\\]|\\.)*"|[^\t "]*)[ \t]*/$1/g;
    
    my $esc         = '\\\\';
    my $space       = '\040';
    my $ctrl        = '\000-\037';
    my $dot         = '\.';
    my $nonASCII    = '\x80-\xff';
    my $CRlist      = '\012\015';
    my $letter      = 'a-zA-Z';
    my $digit       = '\d';
    
    my $atom_char   = qq{ [^$space<>\@,;:".\\[\\]$esc$ctrl$nonASCII] };
    my $atom        = qq{ $atom_char+ };
    my $byte        = qq{ (?: 1?$digit?$digit | 
                              2[0-4]$digit    | 
                              25[0-5]         ) };
    
    my $qtext       = qq{ [^$esc$nonASCII$CRlist"] };
    my $quoted_pair = qq{ $esc [^$nonASCII] };
    my $quoted_str  = qq{ " (?: $qtext | $quoted_pair )* " };
    
    my $word        = qq{ (?: $atom | $quoted_str ) };
    my $ip_address  = qq{ \\[ $byte (?: $dot $byte ){3} \\] };
    my $sub_domain  = qq{ [$letter$digit]
                          [$letter$digit-]{0,61} [$letter$digit]};
    my $top_level   = qq{ (?: $atom_char ){2,4} };
    my $domain_name = qq{ (?: $sub_domain $dot )+ $top_level };
    my $domain      = qq{ (?: $domain_name | $ip_address ) };
    my $local_part  = qq{ $word (?: $dot $word )* };
    my $address     = qq{ $local_part \@ $domain };
    
    return $addr_to_check =~ /^$address$/ox ? $addr_to_check : "";
}

sub send_mail {
	my $email = shift;
    my $email_escaped = URI::Escape::uri_escape($email); 
	my $from_name = "Chimen Chen";
	my $from_email = 'adways@kankan.com'; 

    my $secret_string = &create_mail_account($email);
    
    return unless $secret_string;

	open MAIL, "| /usr/lib/sendmail -t -F'$from_name' -f'$from_email'"
		or die "Could not open sendmail: $!";

	print MAIL <<END_OF_MESSAGE;
To: $email
Subject: Welcome to Kankan!

Welcome to "kankan" bookmark service.
You are already registered to this service.

"kankan" is an email-based bookmark service.

"kankan" gives you a simple way to go through your favorite web pages.
You can email your favorite web pages to yourself.

*** Start "kankan" ***

Please click the following link to register, and follow the instruction as displayed.

http://kankan.com/cgi-bin/bmark.cgi?hl=en&e=$email_escaped&s=$secret_string

*** Unregister ***

Please click the following link to unregister.

http://kankan.com/cgi-bin/delete.cgi?hl=en&e=$email_escaped&s=$secret_string

Thank your for using "kankan" service.

END_OF_MESSAGE

	close MAIL or die "Error closing sendmail: $!";
}

sub create_mail_account {
    my ($email) = @_;

    if ($email) {
        my $db = DB::MailAccounts->new();
        my $rh_account = $db->get_account_by_mail($email);
        if ($rh_account) {
            return $rh_account->{secret};
        } else {
            my $random = new String::Random;
            my $secret_string = $random->randregex('[0-9a-f]{30}');
            $db->insert($email, $secret_string);
            return $secret_string;
        }
    } else {
        return undef;
    }
}

